#!/usr/bin/env python

import cgi
import cgitb; cgitb.enable()  # for troubleshooting
import json
import os
import datetime

# get parameters from environment
form = cgi.FieldStorage()
clid = form.getvalue("lid", "de")
cpid = form.getvalue("pid", "p1")

# open files and parse contents.
regf = open("registry.json", 'r')
regc = json.load(regf)

pagef = open(regc["pages"][cpid], 'r')
pagec = pagef.read()

langf = open(regc["langs"][clid], 'r')
langc = json.load(langf)

# print prolog (MIME-type)
print "Content-type: text/html"
print

# generate dynamic content: create dynamic variables that 
# can be used in templates
vars = langc
vars.update(os.environ)
vars.update({"date":datetime.datetime.now().strftime("%Y-%m-%d %H:%M")})
vars.update({"cpid":cpid})
vars.update({"clid":clid})

# foreach lang-id create a variable that gets replaced with a link
for l in regc["langs"].keys() :
  vars.update({l:"<a href=\"main.py?pid="+cpid+"&lid="+l+"\">"+l+"</a>"})

# foreach page-id create a variable that gets replaced with a link
for p in regc["pages"].keys() :
  vars.update({p:"<a href=\"main.py?pid="+p+"&lid="+clid+"\">"+p+"</a>"})

# replace all variables and render the template
print pagec.format(**vars)
